<?php
/**
 * 示例model（标注表的作用）
 * panglishan
 * 2020.08.13
 */
namespace App\Models\MainDB;

use Illuminate\Database\Eloquent\Model;

class UserData extends Model{

    protected $connection = 'mysql';

    protected $table = 'ln_user_data';     //数据库内完整表名

    protected $primaryKey = 'id';    //主键名

    protected $fillable = [
        'id',      //主键ID
        'user_id',         //用户id
        'user_code',         //用户编号
        'last_user_code',         //上次用户编号(修改之前的)
        'sex',         //1.男  2.女
        'head_picture',         //头像
        'user_photo',         //相册
        'nickname',         //昵称
        'signature',         //签名
        'birthday',         //生日
        'constellation',         //星座
        'profession',         //职业
        'province_id',         //省id
        'city_id',         //市id
        'county_id',         //县id
        'real_name',         //真实姓名
        'identity_number',         //身份证号
        'add_time',         //创建时间
        'intro_voice',         //语音简介
        'intro_voice_time',         //语音简介时长
        'vedio',         //视频
        'vedio_cover',         //视频封面
    ];

    public $timestamps = false;

    public function scopeWithOnly($query, $relation, Array $columns)
    {
        return $query->with([$relation => function ($query) use ($columns){
            $query->select($columns);
        }]);
    }

    public function user()
    {
        return $this->hasOne('App\Models\MainDB\User','user_id','user_id');
    }

    public function good_number()
    {
        return $this->hasOne('App\Models\MainDB\GoodNumber', 'user_id', 'user_id');
    }

    //获取数据集，用user_id作为数组key
    public function getDataWithUserIdMap($userIds, $fields = ['user_code', 'nickname'])
    {
        if (!in_array('user_id', $fields)) $fields[] = 'user_id';

        $userDatas = app('model_user_data')
            ->select($fields)
            ->whereIn('user_id', $userIds)
            ->get()->toArray();
        return array_column($userDatas, null, 'user_id');
    }

    public function getInfoByUserCode($userCode, $fields = ['ud.user_code', 'ud.nickname', 'u.mobile'])
    {
        return $this->from('ln_user_data as ud')
            ->leftJoin('ln_user as u', 'ud.user_id', '=', 'u.user_id')
            ->select($fields)
            ->where('ud.user_code', $userCode)
            ->first();
    }

    //批量查询用户数据
    public function batchQueryByUserIdMap($userIds, $fields = ['user_id', 'user_code', 'nickname'])
    {
        $data = $this->select($fields)
            ->whereIn('user_id', $userIds)
            ->get()->toArray();
        return array_column($data, null, 'user_id');
    }

}